<template>
  <div class="paydetail p-2">
    <el-card>
      <div class="mb-[10px]">
        <el-form ref="ruleFormRef" :model="queryParams" :inline="true">
          <el-form-item label="创建时间" style="width: 340px">
            <el-date-picker
              v-model="dateRange"
              value-format="YYYY-MM-DD"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :disabled-date="disabledDate"
              @calendar-change="dateChange"
              :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="批次号" prop="billNo">
            <el-input v-model="queryParams.billNo" placeholder="请输入批次号" clearable style="width: 270px" />
          </el-form-item>
          <el-form-item label="交易流水号" prop="busNo" label-width="100" v-if="!contentType">
            <el-input v-model="queryParams.busNo" placeholder="请输入交易流水号" clearable style="width: 270px" />
          </el-form-item>
          <el-form-item label="服务商名称" label-width="82" prop="syd_name" v-if="!contentType">
            <el-input v-model="queryParams.params.syd_name" placeholder="请输入服务商名称" clearable style="width: 270px" />
          </el-form-item>
          <el-form-item label="企业名称" prop="mer_name" v-if="!contentType">
            <el-input v-model="queryParams.params.mer_name" placeholder="请输入企业名称" clearable style="width: 270px" />
          </el-form-item>
          <el-form-item label="收款人名称" prop="workerName" v-if="!contentType">
            <el-input v-model="queryParams.workerName" placeholder="请输入收款人名称" clearable style="width: 270px" />
          </el-form-item>
          <el-form-item label="身份证号" prop="cardId" v-if="!contentType">
            <el-input v-model="queryParams.cardId" placeholder="请输入身份证号" clearable style="width: 270px" />
          </el-form-item>
          <el-form-item label="支付通道" prop="passage" v-if="!contentType">
            <el-select v-model="queryParams.passage" placeholder="请选择支付通道" clearable style="width: 270px">
              <el-option v-for="dict in pay_channel" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="打款状态" prop="payStatus" label-width="70" v-if="!contentType">
            <el-select v-model="queryParams.payStatus" placeholder="请选择打款状态" clearable style="width: 270px">
              <el-option v-for="dict in pay_status" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="业务类型" prop="busType" label-width="70" v-if="!contentType">
            <el-select v-model="queryParams.busType" placeholder="请选择业务类型" clearable style="width: 270px">
              <el-option v-for="dict in wxfe_bus_type" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="wayInvoicelist('search')">搜索</el-button>
            <el-button type="primary" icon="Refresh" @click="resetForm(ruleFormRef)">重置</el-button>
            <a class="btn-nav"  @click="contentType = !contentType">
              <span
                v-if="contentType"

                >高级模式
                <i data-v-771b1fc0="" aria-label="图标: down" class="anticon anticon-down"
                  ><svg
                    viewBox="64 64 896 896"
                    data-icon="down"
                    width="1em"
                    height="1em"
                    fill="currentColor"
                    aria-hidden="true"
                    focusable="false"
                    class=""
                  >
                    <path
                      d="M884 256h-75c-5.1 0-9.9 2.5-12.9 6.6L512 654.2 227.9 262.6c-3-4.1-7.8-6.6-12.9-6.6h-75c-6.5 0-10.3 7.4-6.5 12.7l352.6 486.1c12.8 17.6 39 17.6 51.7 0l352.6-486.1c3.9-5.3.1-12.7-6.4-12.7z"
                    ></path></svg></i
              ></span>
              <span
                v-if="!contentType"
                >精简模式
                <i data-v-771b1fc0="" aria-label="图标: up" class="anticon anticon-up"
                  ><svg
                    viewBox="64 64 896 896"
                    data-icon="up"
                    width="1em"
                    height="1em"
                    fill="currentColor"
                    aria-hidden="true"
                    focusable="false"
                    class=""
                  >
                    <path
                      d="M890.5 755.3L537.9 269.2c-12.8-17.6-39-17.6-51.7 0L133.5 755.3A8 8 0 0 0 140 768h75c5.1 0 9.9-2.5 12.9-6.6L512 369.8l284.1 391.6c3 4.1 7.8 6.6 12.9 6.6h75c6.5 0 10.3-7.4 6.5-12.7z"
                    ></path></svg></i
              ></span>
            </a>
          </el-form-item>
        </el-form>
      </div>

      <div>
        <div style="margin-bottom: 10px;">
          <el-space>
            <el-button @click="handleExport"><el-icon class="el-icon--left"><Download /></el-icon>代发明细EXCEL导出</el-button>
            <!-- <el-button @click="handleB2CExport"><el-icon class="el-icon--left"><Download /></el-icon>B2C回单下载</el-button>-->

            <!-- <el-dropdown>
              <span class="el-dropdown-link">
                下载暂存区
                <el-icon class="el-icon--right">
                  <arrow-down />
                </el-icon>
              </span>
              <template #dropdown>
                <el-card>
                  <template #header>
                    <div style="display: flex;justify-content: space-between;">
                      <span> 文件生成后将在系统中保留3天，过期将自动删除 </span>
                      <el-link>刷新</el-link>
                    </div>
                  </template>
                  <el-table></el-table>
                </el-card>
              </template>
            </el-dropdown> -->
          </el-space>
        </div>
        <el-table ref="roleTableRef" v-loading="loading" border :data="operList" id="out-table">
          <el-table-column label="创建时间" align="center" sortable prop="addTime" width="160" />

          <el-table-column label="批次号" align="center" prop="billNo" show-overflow-tooltip width="190" />
          <el-table-column label="交易流水号" align="center" prop="busNo" show-overflow-tooltip width="200" />
          <el-table-column label="企业名称" align="center" show-overflow-tooltip width="190"  prop="merName" >
            <!-- <template #default="scope">
              <el-tooltip :content="scope.row.no" raw-content placement="bottom" effect="light">
                  <div line-clamp="1" truncated>
                    {{ scope.row.no }}
                  </div>
              </el-tooltip>
            </template>-->
          </el-table-column>
          <el-table-column label="服务商名称" align="center" show-overflow-tooltip width="210" prop="sydName"  >
            <!-- <template #default="scope">
              <el-tooltip :content="scope.row.billNos" raw-content placement="bottom" effect="light">
                  <div line-clamp="1" truncated>
                    {{ scope.row.billNos }}
                  </div>
              </el-tooltip>
            </template> -->
          </el-table-column>

          <el-table-column label="打款金额(元)" align="center" prop="amountStr" width="140" >
              <template #default="scope">
                 <span>{{ convertFenToYuan(scope.row.amount) }}</span>
              </template>
          </el-table-column>

          <el-table-column label="收款人" align="center" prop="workerName" width="100" />
          <el-table-column label="收款人身份证号" align="center" prop="cardId" width="140" />
          <el-table-column label="结算账户" prop="bankCard" align="center" width="190">
          </el-table-column>
          <el-table-column label="收款人手机号" align="center" prop="workerPhone" width="140">
          </el-table-column>
          <el-table-column label="结算通道" align="center" prop="passage" width="120">
          </el-table-column>
          <el-table-column label="打款状态" align="center" prop="payStatus" width="100" >
            <template #default="scope">
              <dict-tag :options="pay_status" :value="scope.row.payStatus" />
            </template>
          </el-table-column>
          <el-table-column label="支付时间" align="center" prop="payTime" width="160" />
          <el-table-column label="银行附言" align="center" show-overflow-tooltip prop="billRemark" width="140" />
          <el-table-column label="备注" align="center" show-overflow-tooltip  prop="payRemark" width="140" />
          <el-table-column fixed="right" label="操作" align="center" prop="roleName" width="140">
            <template #default="scope">
              <el-tag type="primary" plain size="small" @click="clickDetail(scope.row)">详情</el-tag>
              <el-tag type="success" v-if="userRole == 9 && scope.row.payStatus == 2 " link plain size="small" @click="repay(scope.row)">补发</el-tag>
              <el-tag type="success" v-if="scope.row.payReceipt" link plain size="small" @click="downL(scope.row)">电子回单</el-tag>
            </template>
          </el-table-column>
        </el-table>
          <pagination
           v-if="total > 0"
           v-model:total="total"
           v-model:page="queryParams.pageNum"
           v-model:limit="queryParams.pageSize"
           @pagination="getList"
          />
      </div>
    </el-card>
    <Details  :openCheck="detailOpen" :txItem="txItem" @dialogClose="dialogClose" />
    <RePay  ref="repayRef" :openCheck="rePayOpen" :item="repayItem" @dialogClose="rePayDialogClose" @dialogSubmit="rePaySubmit" />
  </div>

</template>

<script setup name="payDetail" lang="ts">
  import useUserStore from '@/store/modules/user';
  import {billDetail,repayDetail} from "@/api/settle/payDetail";
  import Details from "@/views/settle/paydetail/detail/detail.vue";
  import RePay from "@/views/settle/paydetail/repay/index.vue";
 import moment from 'moment';

  const { proxy } = getCurrentInstance() as ComponentInternalInstance;
  const { pay_status } = toRefs<any>(proxy?.useDict('pay_status'));
  const { wxfe_bus_type } = toRefs<any>(proxy?.useDict('wxfe_bus_type'));
  const { pay_channel } = toRefs<any>(proxy?.useDict('pay_channel'));


  const router = useRouter();
  const userRole = ref(0);
  const detailOpen = ref(false);
  const txItem = ref({});
  const rePayOpen = ref(false)
  const repayRef = ref();



 const data = reactive({
  queryParams: {
    billNo:'',
    busNo: '',
    params:{
      syd_name:'',
      mer_name:'',
      workerName:'',
      cardId:'',
      begin_date:'',
      end_date:''

    },
    passage:'',
    busType:'',
    payStatus:null,
    pageSize:10,
    pageNum:1,
    orderByColumn:'',
    isAsc:'',
    roleName: ''
  }
});
const { queryParams } = toRefs(data);
const contentType = ref(true) // true 精简模式 , false 高级模式
const loading = ref(false)   //加载动画
const dateRange = ref(['', ''])  //创建时间参数
const invoiceDatalist = ref([])   //获取到的数据列表
const total = ref(0);
const operList = ref([]);
const currentDate = ref(null);
const repayItem = ref({})

const rePayDialogClose = ()=>{

    rePayOpen.value = false;

}


const rePaySubmit = (payload)=>{
    repayDetail(payload).then(res=>{
      if(res.code == 200){
        repayRef.value.hideLoad();
        rePayOpen.value = false;
        proxy?.$modal.msgSuccess(`提交成功!`);

        getList();
      }else{
        proxy?.$modal.msgError(`提交失败!`);
      }
    }).finally(()=>{
        repayRef.value.hideLoading();
    });
}

//补发
const repay = (row:any)=>{
  rePayOpen.value = true;
  repayItem.value = row;

}

const dateChange = (val)=>{
  currentDate.value = val;
}

const disabledDate = (time)=> {
    // 假设我们限制从当前日期开始，最多可以选择三个月
    let today = new Date();

    if(time.getTime() > today.getTime()){
        return true;
    }

    // 如果是开始日期，则不能选择超过三个月后的日期
    // if (currentDate.value) {
    //   console.log(currentDate.value[0])
    //     let date1 = currentDate.value[0];
    //     let threeMonthsLater = new Date(date1);
    //     let threeMonthsLater1 = new Date(date1);
    //     threeMonthsLater.setMonth(date1.getMonth() + 3);
    //     threeMonthsLater1.setMonth(date1.getMonth() - 3);
    //     if(threeMonthsLater.getTime() > today.getTime()){
    //       threeMonthsLater = today;
    //     }
    //     console.log(threeMonthsLater1)
    //     console.log(  time.getTime()  < threeMonthsLater1.getTime()  )

    //     return time.getTime() > threeMonthsLater.getTime() || time.getTime()  < threeMonthsLater1.getTime()  ;
    // }

    return false;
  }

const clickDetail = (item:any)=>{
    detailOpen.value  = true;
    txItem.value = item;
}

const dialogClose = ()=>{
    detailOpen.value  = false;
}

const downL=(row)=>{
  if(!row.payReceipt){
    proxy?.$modal.msgError(`暂无电子回单!`);
    return;
  }
  proxy?.download("/resource/oss/dlurl", {
   url:row.payReceipt,
  }, `${row.workerName}_${row.busNo}_支付凭证.pdf`);

}

const wayInvoicelist = ()=>{
  queryParams.value.pageNum = 1;
  if( dateRange.value && dateRange.value.length > 0){
    queryParams.value.params.begin_date = dateRange.value[0];
    queryParams.value.params.end_date = dateRange.value[1];
  }else{
    queryParams.value.params.begin_date = '';
    queryParams.value.params.end_date = '';
  }

  getList();
}

 /**
  * 查询列表
  */
 const getList = () => {
   loading.value = true
   billDetail(queryParams.value).then(res => {
     operList.value = res.rows
     total.value = res.total
     loading.value = false
   })
 }

const roleTableRef =ref();
 /** 导出按钮操作 */
 const handleExport = () => {

    let columns = roleTableRef.value.columns;
    let fields1 =  [];
    columns.forEach(item=>{
      fields1.push(item.property);
    })



  if(userRole.value == 6){
    proxy?.download("/payment/billDetail/export", {
      ...queryParams.value,
      fields:fields1.join(",")
    }, `代发明细列表_${new Date().getTime()}.xlsx`);

  }else if(userRole.value == 8 || userRole.value == 7){
      proxy?.download("/payment/billDetail/export", {
        ...queryParams.value,
         fields:fields1.join(",")
      }, `代发明细列表_${new Date().getTime()}.xlsx`);
  }else if(userRole.value == 9){
      proxy?.download("/payment/billDetail/export", {
        ...queryParams.value,
         fields:fields1.join(",")
      }, `代发明细列表_${new Date().getTime()}.xlsx`);
  }

 };



 /** 导出按钮操作 */
 const handleB2CExport = () => {
   if(userRole.value == 6){
      proxy?.download("/payment/billDetail/exportB2C", {
        ...queryParams.value,
      }, `代发B2C回单_${new Date().getTime()}.xlsx`);
   }else if(userRole.value == 9){
      proxy?.download("/payment/billDetail/exportB2C", {
        ...queryParams.value,
      }, `代发B2C回单_${new Date().getTime()}.xlsx`);
   }
 };


const test = ()=>{

  var wb = XLXS.utils.table_to_book(document.querySelector("#out-table"), {

  raw: true
  });

  var wbout = XLXS.write(wb, {

  bookType: "xlsx",

  bookSST: true,

  type: "array"

  });

  try {

  fs.saveAs(

  new Blob([wbout], {

  type: "application/octet-stream"

  }),

  `test.xlsx`

  );


  } catch (e) {

  alert(123);


  }

  return wbout;


}


onMounted(() => {
     let curRoleId = useUserStore().curRoleId;
     userRole.value = curRoleId;
      getList();
    });


</script>

<style lang="scss" scoped>
  .paydetail{
    background-color: #eef0f3;

    .btn-nav {
    margin-left: 8px;
    & {
      color: #1890ff;
      text-decoration: none;
      background-color: transparent;
      outline: none;
      cursor: pointer;
      transition: color 0.3s;
    }
    .anticon {
      display: inline-block;
      color: inherit;
      font-style: normal;
      line-height: 0;
      text-align: center;
      text-transform: none;
      vertical-align: -0.125em;
      text-rendering: optimizeLegibility;
      -webkit-font-smoothing: antialiased;
    }
  }
  }
</style>
